package com.ruoyi.peoplegroup.controller;

import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.util.BeanUtil;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.file.FileTypeUtils;
import com.ruoyi.common.core.utils.file.MimeTypeUtils;
import com.ruoyi.peoplegroup.domain.ResearcherinfoHistory;
import com.ruoyi.peoplegroup.service.IPartnerinfoService;
import com.ruoyi.peoplegroup.service.IResearcherinfoHistoryService;
import com.ruoyi.peoplegroup.service.IResearchertypeService;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.RemoteRoleService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysFile;
import com.ruoyi.system.api.domain.SysRole;
import com.ruoyi.system.api.domain.SysUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.peoplegroup.domain.Researcherinfo;
import com.ruoyi.peoplegroup.service.IResearcherinfoService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 科研人员信息Controller
 *
 * @author gw
 * @date 2025-01-08
 */
@RestController
@RequestMapping("/researcherinfo")
public class ResearcherinfoController extends BaseController {
    @Autowired
    private IResearcherinfoService researcherinfoService;

    @Autowired
    private RemoteFileService remoteFileService;
    @Autowired
    private RemoteUserService userService;
    @Autowired
    private IResearchertypeService researchertypeService;
    @Autowired
    private RemoteRoleService roleService;
    @Autowired
    private IPartnerinfoService partnerinfoService;
    @Autowired
    private IResearcherinfoHistoryService researcherinfoHistoryService;


    /**
     * 查询科研人员信息列表
     */
    @RequiresPermissions("peoplegroup:researcherinfo:list")
    @GetMapping("/list")
    public TableDataInfo list(Researcherinfo researcherinfo) {
        startPage();
        List<Researcherinfo> list = researcherinfoService.selectResearcherinfoList(researcherinfo);
    for (Researcherinfo researcherinfo1:list){
    researcherinfo1.setTypeName(researchertypeService.selectResearchertypeByResearcherTypeId(researcherinfo1.getResearcherTypeId()).getTypeName());
    researcherinfo1.setUnitName(partnerinfoService.selectPartnerinfoByPartnerId(researcherinfo1.getPartnerId()).getUnitName());
}
        return getDataTable(list);
    }

    /**
     * 导出科研人员信息列表
     */
    @RequiresPermissions("peoplegroup:researcherinfo:export")
    @Log(title = "科研人员信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Researcherinfo researcherinfo) {
        List<Researcherinfo> list = researcherinfoService.selectResearcherinfoList(researcherinfo);
        ExcelUtil<Researcherinfo> util = new ExcelUtil<Researcherinfo>(Researcherinfo.class);
        util.exportExcel(response, list, "科研人员信息数据");
    }

    /**
     * 获取科研人员信息详细信息
     */
    @RequiresPermissions("peoplegroup:researcherinfo:query")
    @GetMapping(value = "/{researcherId}")
    public AjaxResult getInfo(@PathVariable("researcherId") Long researcherId) {
        return success(researcherinfoService.selectResearcherinfoByResearcherId(researcherId));
    }

    @RequiresPermissions("peoplegroup:researcherinfo:query")
    @GetMapping(value = "/researcherinfo/{researcherId}")
    public R<Researcherinfo> getInfo1(@PathVariable("researcherId") Long researcherId) {
        Researcherinfo researcherinfo = researcherinfoService.selectResearcherinfoByResearcherId(researcherId);
        return R.ok(researcherinfo);
    }


    /**
     * 新增科研人员信息
     */
    @RequiresPermissions("peoplegroup:researcherinfo:add")
    @Log(title = "科研人员信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Researcherinfo researcherinfo) {
        try {
            // 插入科研人员信息
            int researcherInserted = researcherinfoService.insertResearcherinfo(researcherinfo);
            if (researcherInserted > 0) {
                // 创建 SysUser 对象，并填写相关信息
                SysUser sysUser = new SysUser();
                sysUser.setUserName(researcherinfo.getResearcherName()); // 假设科研人员姓名作为用户名
                sysUser.setPassword("admin123"); // 设置默认密码，后续可修改
                sysUser.setEmail(researcherinfo.getEmail()); // 科研人员邮箱
                sysUser.setNickName(researcherinfo.getResearcherName()); // 科研人员姓名作为昵称
                sysUser.setPhonenumber(researcherinfo.getPhone()); // 科研人员电话
                sysUser.setStatus("0"); // 默认状态为正常
                sysUser.setDeptId(researcherinfo.getPartnerId()); // 假设合作单位ID映射到部门ID

                // 调用用户注册接口插入用户信息
                R<Boolean> userRegisterResult = userService.add1(sysUser, SecurityConstants.FROM_SOURCE);

                // 假设请求来源为 web
                if (userRegisterResult.getData()) {
                    // 用户注册成功，开始查询科研人员类型
                    System.out.println("用户注册成功，开始查询科研人员类型");

                    String typename = researchertypeService.selectResearchertypeByResearcherTypeId(researcherinfo.getResearcherTypeId()).getTypeName();
                    System.out.println("查询到科研人员类型名称: " + typename);

                    // 获取角色列表
                    R<List<SysRole>> roleResponse = roleService.selectRoleAll1();
                    List<SysRole> roleList = roleResponse.getData();
                    System.out.println("角色列表: " + roleList);

                    // 遍历角色列表，找到匹配的角色
                    for (SysRole role : roleList) {
                        if (role.getRoleName().equalsIgnoreCase(typename)) {
                            try {
                                // 给用户授权匹配的角色
                                Long userid = sysUser.getUserId();
                                Long [] roleids = new Long[]{role.getRoleId()};
                                userService.insertAuthRole1(userid, roleids);
                                System.out.println("角色分配成功: 用户ID = " + sysUser.getUserId() + ", 角色ID = " + role.getRoleId());
                                return toAjax(true); // 如果科研人员和用户信息插入成功，返回成功响应
                            } catch (Exception e) {
                                System.err.println("角色授权失败，原因: " + e.getMessage());
                                return toAjax(false); // 如果授权失败，返回失败响应
                            }
                        }
                    }

                    // 如果没有匹配的角色
                    System.out.println("未找到匹配的角色，科研人员类型名称: " + typename);
                    return toAjax(false);
                } else {
                    System.err.println("用户注册失败");
                    return toAjax(false); // 用户注册失败，返回失败响应
                }
            } else {
                System.err.println("科研人员信息插入失败");
                return toAjax(false); // 如果科研人员插入失败，返回失败响应
            }
        } catch (Exception e) {
            System.err.println("操作失败，原因: " + e.getMessage());
            return toAjax(false); // 捕获所有异常，返回失败响应
        }
    }


    /**
     * 修改科研人员信息
     */
    @RequiresPermissions("peoplegroup:researcherinfo:edit")
    @Log(title = "科研人员信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Researcherinfo researcherinfo) {
        return toAjax(researcherinfoService.updateResearcherinfo(researcherinfo));
    }

    /**
     * 删除科研人员信息
     */
    @RequiresPermissions("peoplegroup:researcherinfo:remove")
    @Log(title = "科研人员信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{researcherIds}")
    public AjaxResult remove(@PathVariable Long[] researcherIds) {
        return toAjax(researcherinfoService.deleteResearcherinfoByResearcherIds(researcherIds));
    }


    /**
     * 头像上传
     */
    @Log(title = "科研用户头像", businessType = BusinessType.INSERT)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) {
        if (!file.isEmpty()) {
            String extension = FileTypeUtils.getExtension(file);
            if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
                return error("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
            }
            R<SysFile> fileResult = remoteFileService.upload(file);
            if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData())) {
                return error("文件服务异常，请联系管理员");
            }
            String url = fileResult.getData().getUrl();
            AjaxResult ajax = AjaxResult.success();
            ajax.put("imgUrl", url);
            // 更新缓存用户头像
            return ajax;

        }
        return error("上传图片异常，请联系管理员");
    }
}
